import * as vscode from 'vscode';

const activeTerminals = new Map<string, vscode.Terminal>();

/**
 * Registers a new terminal, disposing of any previous terminal with the same name.
 * Also handles cleanup if the terminal is manually closed by the user.
 * @param name A unique name to identify the terminal's purpose (e.g., 'compile', 'sync').
 * @param terminal The VS Code terminal instance to register.
 */
export function registerTerminal(name: string, terminal: vscode.Terminal) {
    // If a terminal with the same purpose already exists, dispose of it.
    if (activeTerminals.has(name)) {
        activeTerminals.get(name)?.dispose();
    }
    activeTerminals.set(name, terminal);

    // Listen for when the terminal is manually closed to remove it from our map.
    const disposable = vscode.window.onDidCloseTerminal(t => {
        if (t === terminal) {
            if (activeTerminals.get(name) === t) {
                activeTerminals.delete(name);
            }
            disposable.dispose();
        }
    });
}

/**
 * Disposes of all terminals created by this extension.
 * Intended to be called from the extension's `deactivate` function.
 */
export function disposeAllTerminals() {
    activeTerminals.forEach(terminal => {
        terminal.dispose();
    });
    activeTerminals.clear();
} 